package com.dmjj.dmjjxt.controller;

import com.dmjj.common.base.BaseController;
import com.dmjj.common.base.LoginEntity;
import com.dmjj.common.fileload.Fileload;
import com.dmjj.common.result.ResultEnum;
import com.dmjj.common.result.ResultObject;
import com.dmjj.common.result.ResultPageObject;
import com.dmjj.common.util.InsertCreatManInfo;
import com.dmjj.common.util.ListCopyToVOUtil;
import com.dmjj.common.util.MapToObject;
import com.dmjj.common.util.PaginationVOUtil;
import com.dmjj.common.vo.ResultPageVO;
import com.dmjj.common.vo.ResultVO;
import com.dmjj.dmjjxt.dto.*;
import com.dmjj.dmjjxt.service.BoothService;
import com.dmjj.dmjjxt.service.ContractService;
import com.dmjj.dmjjxt.service.ProductSeriesService;
import com.dmjj.dmjjxt.service.TenantStandService;
import com.dmjj.dmjjxt.vo.ContractParamVo;
import com.dmjj.dmjjxt.vo.ContractSaveVO;
import com.dmjj.dmjjxt.vo.ContractVO;
import com.dmjj.dmjjxtutil.MyProps;
import com.dmjj.dmjjxtutil.NumberToCN;
import com.dmjj.dmjjxtutil.WordToPDF;
import com.dmjj.dmjjxtutil.WorkUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 合同信息表控制器
 * @Author zhangxue
 * @Date 2019-04-11 14:13:52
 */

@RestController
@Api(tags = "合同信息表控制器")
@RequestMapping("contract")
public class ContractController extends BaseController {

    private static final Log LOGGER = LogFactory.getLog(ContractController.class);

    @Autowired
    private ContractService service;
    @Autowired
    private ResultObject resultObject;
    @Autowired
    private MyProps myProps;
    @Autowired
    private WordToPDF wordToPDF;
    @Autowired
    private ResultPageObject resultPageObject;

    /**
	 * 合同信息表列表
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
	 * @Param
	 * @Return
	 */
    @ApiOperation(value = "合同信息表列表", response = ContractVO.class)
    @PostMapping("list4Page")
    public ResultPageVO<Object> list4Page(
            ContractVO entity,
            @ApiParam(value = "当前页", required = true) @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页显示条数", required = true) @RequestParam(value = "pageSize", defaultValue = "15") Integer pageSize
    ){
        try {
            ContractDTO entityDTO = new ContractDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            List<ContractDTO> list = service.list4Page(entityDTO, pageNum, pageSize);
            List<ContractDTO> list1 = service.listByCondition(entityDTO);
            //总条数
            Integer total = list1.size();
            Integer totalPage = total/pageSize;
            if(total%pageSize!=0){
                totalPage += 1;
            }
            Boolean hasNext = false;
            if(pageNum!=null&&pageNum<totalPage){
                hasNext = true;
            }
            return resultPageObject.success(ResultEnum.SUCCESS.getCode(),ResultEnum.SUCCESS.getMsg(),pageNum,totalPage,pageSize,total,hasNext,list);
        }catch (Exception e) {
            e.printStackTrace();
            return resultPageObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 合同信息表列表（无分页）
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "合同信息表列表（无分页）", response = ContractVO.class)
    @PostMapping("listByCondition")
    public ResultVO<Object> listByCondition(ContractVO entity){
        try {
            ContractDTO entityDTO = new ContractDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            List<ContractDTO> list = service.listByCondition(entityDTO);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), ListCopyToVOUtil.getListToVO(list, ContractDTO.class));
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 合同信息表详细信息
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "合同信息表详细信息", response = ContractVO.class)
    @PostMapping("queryOneByPk")
    public ResultVO<Object> queryOneByPk(@ApiParam(value = "id",required = true) @RequestParam(value = "id") Long id){
        try {
            ContractDTO entityDTO = service.queryOneByPk(id);
            ContractVO entity = new ContractVO();
            BeanUtils.copyProperties(entityDTO, entity);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), entity);
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }


    @Autowired
    private BoothService boothService;
    @Autowired
    private TenantStandService tenantStandService;
    /**
     * 保存合同信息表信息
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @Transactional
    @ApiOperation(value = "保存合同信息表信息", response = ResultVO.class)
    @PostMapping("save")
    public ResultVO<Object> save(ContractSaveVO entity) {
        try {
            ContractDTO entityDTO = new ContractDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            LoginEntity loginEntity = getUserInfo();
            if(loginEntity==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "token过期");
            }
            //获取创建人、创建时间
            entityDTO = InsertCreatManInfo.Update(entityDTO,loginEntity);
            //存入展位信息
            TenantStandDTO tenantStandDTO = new TenantStandDTO();
            tenantStandDTO.setShno(entityDTO.getShno());
            tenantStandDTO.setBrandno(entityDTO.getBrandno());
            tenantStandDTO.setStoretype("1");
            tenantStandDTO.setStore(entityDTO.getStore());
            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            tenantStandDTO.setMangeyear(sdf.format(now));
            tenantStandDTO.setSeriesno(entityDTO.getSeriesno());
            tenantStandDTO.setFloor(entityDTO.getFloor());
            String boothnos = entityDTO.getBoothno();
            //查询摊位面积
            String[] bootharr = boothnos.split(",");
            BoothDTO boothDTO = new BoothDTO();
            Double boothareas = 0.0;
            for(int i=0;i<bootharr.length;i++){
                boothDTO.setBoothno(bootharr[i]);
                BoothDTO resultBoothDTO = boothService.queryAreaByBoothno(boothDTO);
                if(resultBoothDTO==null){
                    return resultObject.error(ResultEnum.FAIL.getCode(), "无该摊位");
                }
                if(resultBoothDTO.getRentalarea()!=null){
                    Double addarea = resultBoothDTO.getRentalarea();
                    boothareas += addarea;
                }
            }
            if(boothareas == null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "该摊位未补全信息");
            }
            tenantStandDTO.setZwarea(boothareas);
            tenantStandDTO.setIslastmange(0);
            tenantStandDTO.setCreatemanname(entityDTO.getCreatemanname());
            tenantStandDTO.setCreatemanno(entityDTO.getCreatemanno());
            Long j = tenantStandService.save(tenantStandDTO);
            String zwno = tenantStandDTO.getZwno();
            entityDTO.setZwno(zwno);
            if(j==1){
                //存入展位信息后 存入合同信息
                Integer i = service.saveContract(entityDTO);
                if(i==1){
                    if(entityDTO!=null) {
                        Map<String,Object> resultMap = new HashMap<String,Object>();
                        resultMap.put("contractno",entityDTO.getContractno());
                        return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),entityDTO);
                    }else {
                        return resultObject.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
                    }

                }else{
                    return resultObject.error(ResultEnum.FAIL.getCode(), "存入合同信息失败");
                }
            }else{
                return resultObject.error(ResultEnum.FAIL.getCode(), "存入展位信息失败");
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 删除合同信息表信息
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "删除合同信息表信息", response = ResultVO.class)
    @PostMapping("delete")
    public ResultVO<Object> delete(@ApiParam(value = "id",required = true) @RequestParam(value = "id") Long id){
        try {
            if(service.delete(id) > 0) {
                return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
            }else {
                return resultObject.success(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }


    @Autowired
    private ProductSeriesService productSeriesService;

    /**
     * @Author zhangxue
     * @Description //TODO 生成合同内容
     * @Date 11:16 2019/4/14
     * @Param
     * @return
     **/
    @ApiOperation(value = "生成合同内容", response = ResultVO.class)
    @PostMapping("saveContractContent")
    public ResultVO<Object> saveContractContent(ContractParamVo entity){
        try {
            ContractParamDTO resultEntity = service.queryContractInfosByContractNo(entity);
            //通过SeriesNo查询SeriesName
            String SeriesNo = resultEntity.getSeriesno();
            String SeriesNameList = "";
            if(SeriesNo!=null&&!"".equals(SeriesNo)){
                String[] SeriesNoArr = SeriesNo.split(",");
                for(int i=0;i<SeriesNoArr.length;i++){
                    ProductSeriesDTO productSeriesDTO = new ProductSeriesDTO();
                    productSeriesDTO.setSeriesno(SeriesNoArr[i]);
                    productSeriesDTO = productSeriesService.queryOneBySeriesNo(productSeriesDTO);
                    SeriesNameList += productSeriesDTO.getSeriesname()+",";
                }
            }else{
                return resultObject.error(ResultEnum.FAIL.getCode(), "该合同缺少产品系列");
            }
            SeriesNameList = SeriesNameList.substring(0,SeriesNameList.length()-1);
            resultEntity.setSeriesnamelist(SeriesNameList);
            //租借时间 rentYear
            String startDate = resultEntity.getRentalstartdate();
            String endDate = resultEntity.getRentalenddate();
            if(startDate==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "该合同缺少租赁开始时间");
            }
            if(endDate==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "该合同缺少租赁截止时间");
            }
            Integer startDateYear = Integer.valueOf(startDate.split("-")[0]);
            Integer endDateYear = Integer.valueOf(endDate.split("-")[0]);
            Integer rentYear = endDateYear - startDateYear;
            resultEntity.setRentyear(String.valueOf(rentYear));
            //月租金计算
            String RentMoney = resultEntity.getRentalmoney();
            if(RentMoney==null|| "".equals(RentMoney)){
                return resultObject.error(ResultEnum.FAIL.getCode(), "该合同缺少日租金");
            }
            Double RentalMoney = Double.valueOf(RentMoney);
            Double RentalRate = Double.valueOf(myProps.getDayToYearRate());
            Double RentalArea = Double.valueOf(resultEntity.getRentalarea());
            Double MonthRentalMoney = RentalMoney * RentalRate*RentalArea;
            MonthRentalMoney = NumberToCN.formatDouble1(MonthRentalMoney);
            resultEntity.setMonthmoney(String.valueOf(MonthRentalMoney));
            //月租金大写
            BigDecimal numberOfMoney = new BigDecimal(MonthRentalMoney);
            String uppermonthmoney = NumberToCN.number2CNMontrayUnit(numberOfMoney);
            resultEntity.setUppermonthmoney(uppermonthmoney);
            //合同定金大写
            String ContractMoney = resultEntity.getContractmoney();
            if(ContractMoney==null|| "".equals(ContractMoney)){
                return resultObject.error(ResultEnum.FAIL.getCode(), "该合同缺少合同定金");
            }
            Double ContractMoneyDouble = Double.valueOf(ContractMoney);
            BigDecimal ContractMoneyDecimal = new BigDecimal(ContractMoneyDouble);
            String ContractMoneyString = NumberToCN.number2CNMontrayUnit(ContractMoneyDecimal);
            resultEntity.setUppercontractmoney(ContractMoneyString);


            Map<String, String> map = MapToObject.objectToMapString(resultEntity);
            //将生成临时word文件放到E盘下
            WorkUtil.getBuild(myProps.getContractUrl1(),map,myProps.getContractExportUrl1());
            //将生成word文件转化为pdf文件
            long currentTime=System.currentTimeMillis();
            String resultUrl = myProps.getContractPdfUrl()+resultEntity.getShno()+"/"+currentTime+".pdf";
            String saveUrl = "/"+resultEntity.getShno()+"/"+currentTime+".pdf";
            Boolean isSuccess = wordToPDF.WordToPDF(myProps.getContractExportUrl1(),resultUrl);
            if(isSuccess){
                ContractDTO entityDTO = new ContractDTO();
                BeanUtils.copyProperties(resultEntity, entityDTO);
                entityDTO.setContractno(resultEntity.getContractno());
                entityDTO.setContracturl(saveUrl);
                Integer isSuccessUpdate = service.updateContractUrl(entityDTO);
                if(isSuccessUpdate == 1){
                    return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),entityDTO);

                }else{
                    return resultObject.error(ResultEnum.FAIL.getCode(), "保存合同信息失败");
                }
            }else{
                return resultObject.error(ResultEnum.FAIL.getCode(), "生成合同失败");
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }finally {
            Fileload.delete(myProps.getContractExportUrl1());
        }
    }

}